package com.edu.cdp.interceptors;

import com.edu.cdp.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Map;

/**
 * 登录拦截器
 * 拦截器执行顺序：
 *          DispatcherServlet -> preHandle -> Controller -> afterCompletion -> postHandle -> DispatcherServlet
 * 拦截器只拦截spring中的资源
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 令牌验证
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasLength(token)) {
            log.info("令牌为空，拦截请求");
            response.setStatus(401);
            return false;
        }
        try {
            //
            Map<String, Object> claims = JwtUtil.parseToken(token);
            log.info("验证token：claims:{}", claims);

            return true;
        } catch (Exception e) {
            response.setStatus(401);
            log.error("验证token失败：{}", e.getMessage());

            return false;
        }
    }
}
